<template>
  <div class="unit-tab">
    <div class="operation-bar">
      <!-- 操作按钮区域 -->
      <action-buttons
          :buttons="buttonsConfig"
          @add="handleAdd"
          @delete="handleDelete"
          @import="handleImport"
          @export="handleExport"
          @viewLog="handleViewLog"
      />


      <div class="search-box">
        <el-input
            v-model="searchKeyword"
            placeholder="请输入单位名称"
            class="search-input"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
        />
      </div>
    </div>
    <div class="main-content">
      <!-- 表格区域 -->
      <custom-table
          :data="tableData"
          :columns="tableColumns"
          :loading="tableLoading"
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :showCustomColumnBtn="false"
      >
        <!-- 状态列的自定义插槽 -->
        <template #status="{ row }">
          <el-tag :type="row.status === '启用' ? 'success' : 'info'">
            {{ row.status }}
          </el-tag>
        </template>

        <!-- 操作列 -->
        <template #operation="{ row }">
          <theme-button link @click="handleFormEdit(row)">编辑</theme-button>
        </template>
      </custom-table>
    </div>
    <el-dialog
        :title="isEdit ? '编辑单位' : '新增单位'"
        v-model="visible"
        width="450px"
        :close-on-click-modal="false"
    >
      <el-form style="margin: 20px 20px 20px 0" :model="form" label-width="80px">
        <el-form-item label="单位名称" required>
          <el-input v-model="form.name" placeholder="请输入单位名称"/>
        </el-form-item>
        <div class="conversion-rate">
          <div class="unit-add-btn">
            <el-button type="primary" size="small" @click="handleAddUnit">添加单位层级</el-button>
          </div>
          <el-table :data="unitData" border style="width: 100%">
            <el-table-column label="单位层级" width="110" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.name" placeholder="输入单位名称"/>
              </template>
            </el-table-column>
            <el-table-column label="换算率" align="center">
              <template #default="scope">
                <el-input-number
                    v-model="scope.row.num"
                    :min="0"
                    :precision="0"
                    controls-position="right"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="70" align="center">
              <template #default="scope">
                <el-button
                    type="danger"
                    size="small"
                    @click="handleRemoveUnit(scope.$index)"
                    :icon="Delete"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {ref} from 'vue'
import {Search, Delete} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import ActionButtons from "@/components/action-buttons/action-buttons.vue";

// 搜索关键词
const searchKeyword = ref('')

// 处理搜索
const handleSearch = () => {
  console.log('搜索关键词:', searchKeyword.value)
}

const handleDelete = (row) => {

}

// 其他功能保持不变
const handleImport = () => {
  ElMessage.success('点击了导入按钮')
}
const handleExport = () => {
  ElMessage.success('点击了导出按钮')
}
const handleViewLog = () => {
  ElMessage.success('点击了日志按钮')
}


// 操作按钮配置
const buttonsConfig = ref({
  add: {visible: true, order: 1, type: 'success'},
  edit: {visible: false, order: 2},
  delete: {visible: true, order: 3, type: 'danger'},
  import: {visible: false, order: 4},
  export: {visible: false, order: 5},
  viewLog: {visible: true, order: 6},
  enable: {visible: false, order: 2},
  disable: {visible: false, order: 3},
})

// 表格加载状态
const tableLoading = ref(false)
// 表格列配置
const tableColumns = [
  {prop: 'name', label: '单位名称', width: 150, visible: true},
  {prop: 'code', label: '换算关系', minWidth: '120', visible: true},
  {prop: 'barcode', label: '创建人', width: 150, minWidth: '150', visible: true},
  {prop: 'owner', label: '创建时间', width: 200, minWidth: '200', visible: true},
  {prop: 'operation', label: '操作', width: '60', minWidth: '160', fixed: 'right', visible: true}
]
// 表格数据
const tableData = ref([
  {
    id: 1,
    code: '1包=10张，1箱=100张',
    name: '张',
    owner: '货主A',
  },
  {
    id: 2,
    code: '1打=10页，1吖=100页',
    name: '页',
    owner: '货主B',
  }
])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

// 分页大小变更事件
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTableData()
}

// 页码变更事件
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTableData()
}

// 表格多选事件
// 选中的行数据
const selectedRows = ref([])
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}
// 加载
const fetchTableData = () => {
}

const visible = ref(false)
const isEdit = ref(false)
const form = ref({
  name: '',
})
const unitData = ref([])

// 打开编辑弹窗
const handleFormEdit = (row) => {
  form.value = {...row}
  // 解析已有的换算关系
  if (row.code) {
    unitData.value = parseCodeToUnit(row.code)
    console.log(unitData.value)
  }
  isEdit.value = true
  visible.value = true
}

// 打开新增弹窗
const handleAdd = () => {
  isEdit.value = false
  visible.value = true
  // 重置表单
  form.value = {
    name: ''
  }
  // 初始化换算关系
  unitData.value = []
}

// 将code字符串解析为unitData格式
const parseCodeToUnit = (code) => {
  const unitPairs = code.split('，');
  return unitPairs.map(pair => {
    const [left, right] = pair.split('=');
    const num = parseInt(right.replace(/\D/g, ''));
    const name = left.replace(/\d/g, '');
    return {num, name};
  });
}

// 将unitData转换为code字符串格式
const formatUnitToCode = (unitArray) => {
  if (!Array.isArray(unitArray) || unitArray.length === 0) return ''
  return unitArray
      .map(item => `1${item.name}=${item.num}${form.value.name}`)
      .join('，')
}

// 确认按钮处理
const handleConfirm = () => {
  if (!form.value.name) {
    ElMessage.warning('请输入单位名称')
    return
  }

  // 验证换算率
  const hasInvalidRate = unitData.value.some(item => !item.num)
  if (hasInvalidRate) {
    ElMessage.warning('请填写完整的换算率')
    return
  }

  // 生成code字符串
  const codeStr = formatUnitToCode(unitData.value)

  // 更新tableData
  if (isEdit.value) {
    // 编辑模式：更新现有数据
    tableData.value = tableData.value.map(item => {
      if (item.id === form.value.id) {
        return {
          ...form.value,
          code: codeStr
        }
      }
      return item
    })
  } else {
    // 新增模式：添加新数据
    tableData.value.push({
      name: form.value.name,
      code: codeStr
    })
  }

  visible.value = false
  ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
}

// 添加单位层级
const handleAddUnit = () => {
  unitData.value.push({
    name: '',
    num: 1  // 默认换算率为1
  })
}

// 删除单位层级
const handleRemoveUnit = (index) => {
  if (unitData.value.length > 0) {
    unitData.value.splice(index, 1)
  }
}

</script>
<style scoped lang="scss">
.unit-tab {
  .operation-bar {
    margin-bottom: 0;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    align-items: flex-start;

    .search-box {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-left: auto;

      .search-input {
        width: 230px;
      }
    }
  }

  .main-content {
    background: #fff;
    border-radius: 4px;
    min-height: 400px;
    margin-top: -20px;
  }

  .conversion-rate {
    width: 100%;

    .el-input-number {
    }
  }

  .unit-add-btn {
    margin-bottom: 10px;
    text-align: right;
  }
}
</style> 